package com.example.androidframework.ui.mall

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.example.androidframework.R
import com.example.androidframework.databinding.FragmentMallBinding
import com.martin.lib_base.base.BaseFragment
import com.martin.lib_base.ktx.loadMore
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.ktx.logw
import com.martin.lib_base.ktx.refresh
import com.martin.lib_base.ktx.setItemCount
import com.martin.lib_base.ui.SpacesItemDecoration
import com.martin.lib_base.ui.dp
import com.martin.lib_base.widget.RadiusImageBanner
import com.xuexiang.xui.widget.banner.widget.banner.BannerItem
import com.xuexiang.xui.widget.banner.widget.banner.base.BaseIndicatorBanner
import com.xuexiang.xui.widget.textview.MarqueeTextView
import com.xuexiang.xui.widget.textview.marqueen.DisplayEntity
import kotlinx.coroutines.launch

class MallFragment : BaseFragment<FragmentMallBinding, MallViewModel>() {
    var simpleImageBanner: RadiusImageBanner? = null


    override fun getViewModelClass(): Class<MallViewModel> {
        return MallViewModel::class.java
    }

    override fun layoutId(): Int {
        return R.layout.fragment_mall
    }

    override fun initOnViewCreated() {
        binding.viewModel = viewModel

        // 请求数据
        viewModel.requestData()

        lifecycleScope.launch {
            viewModel.mallData.collect {
                logw("首页数据请求成功")
                if (!viewModel.isLoadMore) {
                    // 轮播图
                    setupBanner()
                    // 开启消息跑马灯
                    startMarquee()
                    // 分类标题
                    categoryTabs()
                    // 积分专区
                    scoreZone()
                }
                // 精选热卖
                hotGoods()

                // 设置刷新
                binding.srl.setOnRefreshListener {
                    viewModel.p = 1
                    viewModel.isLoadMore = false
                    viewModel.requestData()
                    binding.srl.finishRefresh()
                }
                binding.srl.setOnLoadMoreListener {
                    viewModel.p++
                    viewModel.isLoadMore = true
                    viewModel.requestData()

                    if (viewModel.mallData.value.recommend_goods_list.isNullOrEmpty()) {
                        binding.srl.finishLoadMoreWithNoMoreData()
                    } else {
                        binding.srl.finishLoadMore()
                    }
                }
            }
        }

        // 模拟请求数据
        Handler(Looper.myLooper()!!).postDelayed({
            // 修改消息数量
            viewModel.postMessageCount(3)
            loge("messageCount === ${viewModel.messageCount.value}")
        }, 1000)

        // 监听消息数量
        viewModel.observeMessageCount { count ->
            loge("message Count === $count")
            binding.tvMsgCount.text = count.toString()
        }
    }

    /**
     * 轮播图
     */
    private fun setupBanner() {
        viewModel.mallData.value.slide?.let {
            // 组装轮播数据
            val bannerList = mutableListOf<BannerItem>()
            for (element in it) {
                val bannerItem = BannerItem()
                bannerItem.imgUrl = element.slide_pic
                bannerItem.title = ""
                bannerList.add(bannerItem)
            }

            // 轮播图
            simpleImageBanner = binding.banner
            simpleImageBanner?.setSource(bannerList)
                ?.setIndicatorStyle(BaseIndicatorBanner.STYLE_CORNER_RECTANGLE)
                ?.setIsOnePageLoop(false)?.startScroll()
            simpleImageBanner?.setOnItemClickListener { view, item, position ->
                loge("点击轮播图index = $position")
            }
            // 自定义轮播图指示器
            binding.indicatorBox.removeAllViews()
            binding.indicatorBox.removeAllViewsInLayout()
            bannerList.forEachIndexed { index, bannerItem ->
                val relativeLayout = RelativeLayout(context)
                val layoutParams =
                    RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 8)
                relativeLayout.layoutParams = layoutParams
                relativeLayout.setPadding(0, 0, if (index == bannerList.size - 1) 0 else 15, 0)

                val view = View(requireContext())
                val layoutParams1 = LinearLayout.LayoutParams(if (index == 0) 40 else 18, 8)
//            view.setBackgroundColor(Color.WHITE)
                view.layoutParams = layoutParams1

                // 设置圆角
                val gradientDrawable = GradientDrawable()
                gradientDrawable.setColor(Color.WHITE)
                gradientDrawable.cornerRadius = 4f
                view.background = gradientDrawable

                relativeLayout.addView(view)
                binding.indicatorBox.addView(relativeLayout)
            }

            simpleImageBanner?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                    bannerList.forEachIndexed { index, bannerItem ->
                        val view =
                            (binding.indicatorBox.getChildAt(index) as RelativeLayout).getChildAt(0)
                        // 设置圆角
                        val gradientDrawable = GradientDrawable()
                        gradientDrawable.setColor(
                            if (index == position) Color.WHITE else Color.parseColor(
                                "#80ffffff"
                            )
                        )
                        gradientDrawable.cornerRadius = 4f
                        view.background = gradientDrawable
//                    view.setBackgroundColor(if (index == position) Color.WHITE else Color.parseColor("#80ffffff"))
                        // 注意: 此处是 RelativeLayout
                        val layoutParams2 =
                            RelativeLayout.LayoutParams(if (index == position) 40 else 18, 8)
                        view.layoutParams = layoutParams2
                    }
                }

                override fun onPageScrollStateChanged(state: Int) {

                }

            })
        }
    }

    /**
     * 消息跑马灯
     */
    private fun startMarquee() {
        binding.tipContent.startSimpleRoll(
            arrayListOf(
                "这是第一条跑马灯消息",
                "这是第二条跑马灯消息",
                "这是第三条跑马灯消息",
                "这是第四条跑马灯消息",
            )
        )

        binding.tipContent.setOnMarqueeListener(object : MarqueeTextView.OnMarqueeListener {
            override fun onStartMarquee(displayEntity: DisplayEntity?, index: Int): DisplayEntity? {
                return displayEntity
            }

            override fun onMarqueeFinished(displayDatas: MutableList<DisplayEntity>?): MutableList<DisplayEntity>? {
                return displayDatas
            }

        })
    }

    /**
     * 分类标题
     */
    private fun categoryTabs() {
        viewModel.mallData.value.shop_class?.let {
            binding.cateTab.removeAllViews()
            for (index in it.indices) {
                val bean = it[index]
                val textView = TextView(context)
                textView.text = bean.gc_name
                textView.setPadding(0, 0, if (index == it.size - 1) 0 else 50, 0)
                binding.cateTab.addView(textView)

                if (index == 0 && bean.parent_list.isNotEmpty()) {
                    // 商品分类数据
                    binding.rvGoodsType.refresh(
                        bean.parent_list
                    )
                }
            }


            binding.cateTab.configTabLayoutConfig {
                // 切换事件
                onSelectIndexChange =
                    { fromIndex: Int, selectIndexList: List<Int>, reselect: Boolean, fromUser: Boolean ->
                        val position: Int = selectIndexList.first()
                        loge("fromIndex = $fromIndex, position = $position")
                        val bean = it[position]
                        // 商品分类数据
                        binding.rvGoodsType.refresh(
                            bean.parent_list
                        )
                    }
            }
        }

    }

    /**
     * 积分专区
     */
    private fun scoreZone() {
        // 设置Item的上方和右方的间距
        binding.scoreRv.addItemDecoration(SpacesItemDecoration(10))
        // 设置左侧间距
        binding.scoreRv.setPadding(10.dp, 0, 0, 0)

        viewModel.mallData.value.bd_goods_list?.let {
            // 限制item数量
            val size = if (it.size > 8) 8 else it.size
            binding.scoreRv.setItemCount(size)
            binding.scoreRv.refresh(it)
        }
    }

    /**
     * 精选热卖
     */
    private fun hotGoods() {
        // 设置间距
        binding.hotGoods.addItemDecoration(SpacesItemDecoration(10))
        binding.hotGoods.setPadding(10, 0, 0, 0)

        viewModel.mallData.value.recommend_goods_list?.let {
            if (!viewModel.isLoadMore) {
                binding.hotGoods.refresh(it)
            } else {
                binding.hotGoods.loadMore(it)
            }
        }
    }


    companion object {
        fun getInstance(): Fragment {
            return MallFragment()
        }
    }
}